<?php

namespace app\index\controller;

use app\index\job\JobActivity;
use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Queue;
use think\Request;
use think\Validate;

class Api extends Controller
{
    // 账户API密码
    private $secret_id = 'ug1wejpub2h82gjco3ed';
    private $secret_key = 'pr4xtpt4kt617k9yheto93phzryzx2ei';
    // 订单API密码
    private $secret_id_order = 'o9czi9hdy20fbg1jrxqx';
    private $secret_key_order = 'zn4l5dpfq5nlltnk2xvfbel51rx0juwp';

    /**
     * 获得【账户API】密钥令牌
     * @param $type int 1：账户API，2：订单API
     * */
    public function getSecretToken($type = 1)
    {
        $file_name = $type == 1 ? 'secret_token.txt' : 'secret_token_order.txt';

        $secret_token = file_get_contents(RUNTIME_PATH . $file_name);
        if ($secret_token) {
            $status = $this->checkSecretToken($secret_token, $type);
            if ($status) return $secret_token;
        }

        $url = 'https://auth.kdlapi.com/api/get_secret_token';
        $data = [
            'secret_id' => $type == 1 ? $this->secret_id : $this->secret_id_order,
            'secret_key' => $type == 1 ? $this->secret_key : $this->secret_key_order
        ];
        $res = httpsRequest($url, $data);
        $res = json_decode($res, true);
        if ($res['code'] == 0) {
            $secret_token = $res['data']['secret_token'];
            file_put_contents(RUNTIME_PATH . $file_name, $secret_token);

            return $secret_token ? : false;
        } else {
            return false;
        }
    }

    /**
     * 检测密钥令牌
     * @param $secret_token string 密钥令牌
     * @param $type         int 1：账户API，2：订单API
     * */
    public function checkSecretToken($secret_token, $type = 1)
    {
        $url = 'https://auth.kdlapi.com/api/check_secret_token';
        $data = [
            'secret_id' => $type == 1 ? $this->secret_id : $this->secret_id_order,
            'secret_token' => $secret_token
        ];
        $res = httpsRequest($url, $data);
        $res = json_decode($res, true);
        if ($res['code'] == 0) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 获取隧道代理Pro省份编码
     * */
    public function getProvinceCode()
    {
        $url = 'https://tps.kdlapi.com/api/gettpsprovcode';
        $data = [
            'secret_id' => $this->secret_id_order,
            'signature' => $this->getSecretToken(2)
        ];

        $res = httpsRequest($url, $data);
        $res = json_decode($res, true);
        if ($res['code'] == 0) {
            $province_code_list = $res['data'];
            if ($province_code_list) {
                $province_code_data = [];
                foreach ($province_code_list as $province_name => $province_code) {
                    $province_code_data[] = [
                        'name' => $province_name,
                        'code' => $province_code
                    ];

                }
                Db::name('region_code')->insertAll($province_code_data);
            }

        } else {
            return false;
        }
    }

    public function provinceList()
    {
        $list = Db::name('region_code')->where(['prov' => 0, 'is_ok' => 0])->order('code asc')->limit(4)->select();
        if ($list) {
            foreach ($list as &$v) {
                $this->insertCityData($v['code']);
            }
        }
    }

    public function insertCityData($province_code)
    {
        $res = Db::name('region_code')->where('code', $province_code)->setField('is_ok', 1);
        if ($res) {
            $city_code_list = $this->getCityCode($province_code);
            if ($city_code_list) {
                $city_code_data = [];
                foreach ($city_code_list as $city_name => $city_code) {
                    $city_code_data[] = [
                        'name' => $city_name,
                        'code' => $city_code,
                        'prov' => $province_code
                    ];
                }
                Db::name('region_code')->insertAll($city_code_data);
            }
        } else {
            echo '失败';
        }
    }

    /**
     * 获取隧道代理Pro城市编码
     * */
    public function getCityCode($prov)
    {
        if (empty($prov)) return false;

        $url = 'https://tps.kdlapi.com/api/gettpscitycode';
        $data = [
            'secret_id' => $this->secret_id_order,
            'signature' => $this->getSecretToken(2),
            'prov' => $prov
        ];

        $res = httpsRequest($url, $data);
        $res = json_decode($res, true);
        if ($res['code'] == 0) {
            return $res['data'];
        } else {
            return false;
        }
    }

    public function getUa()
    {
        $url = 'https://dev.kdlapi.com/api/getua?secret_id=o1fjh1re9o28876h7c08';
        $data = [
            'secret_id' => $this->secret_id_order,
            'signature' => $this->getSecretToken(2),
            'num' => 1
        ];
        $res = httpsRequest($url, $data);
        $res = json_decode($res, true);

        return $res['data']['ua_list'][0];
    }

    public function gettpspro()
    {
        $url = 'https://tps.kdlapi.com/api/gettpspro';
        $data = [
            'secret_id' => $this->secret_id_order,
            'signature' => $this->getSecretToken(2),
            'num' => 1
        ];
        $res = httpsRequest($url, $data);
        echo "<pre>";
        print_r($res);
        exit;
        $res = json_decode($res, true);
        echo "<pre>";
        print_r($res);
        exit;
    }

    public function test()
    {
        //要访问的目标页面
        $page_url = "https://www.wjx.cn/vm/mOvrHDy.aspx";


        $ch = curl_init();
        $tunnelhost = "z621.kdltpspro.com";
        $tunnelport = "15818";
        $proxy = $tunnelhost.":".$tunnelport;

        //隧道用户名密码
        $username = "t12741771412559-city-420100";
        $password = "zhw0ma7h";

        //$ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $page_url);

        //发送post请求
        // $requestData["post"] = "send post request";
        // curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($requestData));

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        //设置代理
        curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
        curl_setopt($ch, CURLOPT_PROXY, $proxy);
        //设置代理用户名密码
        curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$username}:{$password}");

        //自定义header
        $headers = array();
        $headers["user-agent"] = $this->getUa();
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        //自定义cookie
        curl_setopt($ch, CURLOPT_COOKIE,'');

        curl_setopt($ch, CURLOPT_ENCODING, 'gzip'); //使用gzip压缩传输数据让访问更快

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);

        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $result = curl_exec($ch);
        $info = curl_getinfo($ch);
        curl_close($ch);

        echo "$result"; // 使用请求页面方式执行时，打印变量需要加引号
        echo "\n\nfetch ".$info['url']."\ntimeuse: ".$info['total_time']."s\n\n";

    }

    public function test2()
    {
        startChromeDriver();
    }

}
